package org.luo.lan.server.handlers;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.luo.lan.common.handler.ControlTypeConstant;
import org.luo.lan.common.handler.Request;
import org.luo.lan.common.util.StringUtils;
import org.luo.lan.server.constants.AttrConstants;
import org.luo.lan.server.factory.SessionFactory;

/**
 * @Auther: luobiao
 * @Date: 2020/9/19 09:15
 * @Description:
 */
@Slf4j
public class ServerProxyHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) {
        byte[] bytes=new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
/*        log.debug("------------------代理响应内容begin-------------------");
        log.debug(new String(bytes));
        log.debug("------------------代理响应内容end-------------------");*/
        Channel bridgeChannel = ctx.channel().attr(AttrConstants.BRIDGE_CHANNEL).get();
        String sessionKey = ctx.channel().attr(AttrConstants.SEESION_KEY).get();
        bridgeChannel.writeAndFlush(Request.SUCCESS(ControlTypeConstant.PROXY, bytes).addHeader(sessionKey));
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        NioSocketChannel channel=(NioSocketChannel)ctx.channel();
        String sessionKey=channel.attr(AttrConstants.SEESION_KEY).get();
        if (StringUtils.isNotBlank(sessionKey)) {
            Boolean isManualClose=channel.attr(AttrConstants.IS_MANUAL_CLOSE).get();
            if (!isManualClose) {
                Channel bridgeChannel=channel.attr(AttrConstants.BRIDGE_CHANNEL).get();
                if (bridgeChannel != null) {
                    bridgeChannel.writeAndFlush(Request.SUCCESS(ControlTypeConstant.CLOSE_SESSION, "服务器端请求关闭代理会话通道！").addHeader(sessionKey));
                }
            }
            SessionFactory.INSTANCE.removeSession(sessionKey);
        }
    }
}
